package com.cade.agriculturemall.view.personalCenter.ordersManage.OrderItems;

import android.content.DialogInterface;
import android.content.Entity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AlertDialogLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseActivity;
import com.cade.agriculturemall.base.BaseViewHolder;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.utils.ConverUtil;
import com.cade.agriculturemall.view.shoppingCar.selecpaystatus.SelectPayStatusActivity;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

public class OrderActivity extends BaseActivity<OrderContract.IPresenter> implements OrderContract.IView, View.OnClickListener {
    private String dealNo = "";
    private String orderNo = "";
    private OrderEntity orderEntity = new OrderEntity();
    private List<OrderViewModel> models = new ArrayList<>();
    private OrderAdapter mAdapter = new OrderAdapter(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        setupToolbar(true);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.order_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        if (orderEntity.getObjectId() != null) {
            recyclerView.setAdapter(mAdapter);
        }
        View footView = findViewById(R.id.order_foot_include);
        tvPay = (TextView) footView.findViewById(R.id.item_order_price_tv_pay_certain);
        tvDelete = (TextView) footView.findViewById(R.id.item_order_price_btn_delete);
        tvLogistics = (TextView) footView.findViewById(R.id.item_order_price_btn_logistics);
        tvReturn = (TextView) footView.findViewById(R.id.item_order_price_btn_return);
        tvCancel = (TextView) footView.findViewById(R.id.item_order_price_btn_cancel);
        tvToPay = (TextView) footView.findViewById(R.id.item_order_price_btn_pay);
        tvPost = (TextView) footView.findViewById(R.id.item_order_price_tv_info_post);

        tvDelete.setOnClickListener(this);
        tvLogistics.setOnClickListener(this);
        tvReturn.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        tvToPay.setOnClickListener(this);
        tvPost.setOnClickListener(this);
    }

    TextView tvDelete, tvLogistics, tvReturn, tvCancel, tvToPay, tvPost, tvPay;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.item_order_price_btn_delete:
                mPresenter.goodsDelete(orderEntity);
                showDialog();
                break;
            case R.id.item_order_price_btn_logistics:
                Toast.makeText(this, "跳转物流页面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_order_price_btn_return:
                Toast.makeText(this, "跳转退货页面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_order_price_btn_cancel:
                showDialog();
                break;
            case R.id.item_order_price_btn_pay:
                Toast.makeText(this, "未支付,去支付页面", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, SelectPayStatusActivity.class);
                ArrayList<String> list = new ArrayList<>();
                list.add(orderEntity.getObjectId());
                intent.putStringArrayListExtra("orderList", list);
                intent.putExtra("orderId", orderEntity.getOrderId());
                startActivity(intent);
                break;
            case R.id.item_order_price_tv_info_post:
                Toast.makeText(this, "已提醒卖家发货", Toast.LENGTH_LONG).show();
                break;
        }

    }

    @Override
    public void setupView() {

    }

    @Override
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("删除后订单不可恢复，是否继续删除订单？").setTitle("确认删除订单？").setPositiveButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                mPresenter.goodsDelete(orderEntity);
            }
        });
        builder.show();
    }

    @Override
    public void deleteSuccess() {
        finish();
        Toast.makeText(this, "订单删除成功", Toast.LENGTH_SHORT);
    }

    @Override
    public void deleteFail() {
        finish();
        Toast.makeText(this, "订单不可删除", Toast.LENGTH_SHORT);
    }

    @Override
    public void setupEvent() {

    }

    /**
     * dealNo：按处理单号查询
     * orderNo： 按订单单号查询
     */
    @Override
    public void setupData() {
        dealNo = getIntent().getStringExtra("dealNo"); //String 8215199809173929aa5     0615199812860519aa5
        orderNo = getIntent().getStringExtra("orderNo");//String 361519980917392
        if (!TextUtils.isEmpty(dealNo)) {
            mPresenter.downLoadOrderInfo(dealNo, null);      //按处理编号查询
        }
        if (!TextUtils.isEmpty(orderNo)) {
            mPresenter.downLoadOrderInfo(null, orderNo);
        } else {    //按订单编号查询
            Toast.makeText(mActivity, "orderNo、dealNo 为空 ", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public OrderContract.IPresenter setupPresenter() {
        return new OrderPresenter(this);
    }

    @Override
    public void getPro(List<OrderEntity> orderList, List<ShoppingCarsEntity> list) {
        if (list != null)
            if (list.size() != 0 && orderList.size() != 0) {
                orderEntity = orderList.get(0);
                setFootView(orderEntity.getOrderStatus());
                models.add(new OrderViewModel<>(OrderViewModel.TYPE_STATUS, orderEntity));
//            setStatusTime(orderEntity);
                AddressEntity addressEntity = orderEntity.getAddressId();
                models.add(new OrderViewModel<>(OrderViewModel.TYPE_ADRESS, addressEntity));
                HashMap<String, List<ShoppingCarsEntity>> hashMap = new HashMap<>();
                for (ShoppingCarsEntity entity : list) {
                    List<ShoppingCarsEntity> listShoppingCarsEntity = null;
                    if (hashMap.containsKey(entity.getShoper())) {
                        listShoppingCarsEntity = hashMap.get(entity.getShoper());
                    }
                    if (listShoppingCarsEntity == null) {
                        listShoppingCarsEntity = new ArrayList<>();
                        hashMap.put(entity.getShoper(), listShoppingCarsEntity);
                    }
                    listShoppingCarsEntity.add(entity);
                }
                int pos = 0;
                for (String shoper : hashMap.keySet()) {
                    orderEntity = orderList.get(pos);
                    pos++;
                    if (!TextUtils.isEmpty(orderEntity.getRemarks()) | orderEntity.getRemarks() == null) {
                        models.add(new OrderViewModel(OrderViewModel.TYPE_REMARK, orderEntity.getRemarks()));
                    }
                    models.add(new OrderViewModel(OrderViewModel.TYPE_SJ, hashMap.get(shoper).get(0).getShoperLongName()));

//                    models.add(new OrderViewModel(OrderViewModel.TYPE_SJ, hashMap.get(shoper)));
                    for (ShoppingCarsEntity entity : hashMap.get(shoper)) {
                        OrderViewModel viewModel = new OrderViewModel(OrderViewModel.TYPE_CP, entity);
                        models.add(viewModel);
                    }
                    models.add(new OrderViewModel<>(OrderViewModel.TYPE_ITEMS, orderEntity));
                }
                models.add(new OrderViewModel<>(OrderViewModel.TYPE_COUNT, orderEntity.getOrderPrice()));
//                models.add(new OrderViewModel<>(OrderViewModel.TYPE_SJ_FOOTER, orderEntity.getOrderPrice()));
                tvPay.setText(TextUtils.isEmpty(orderEntity.getOrderPayMoney()) ? "￥" + orderEntity.getOrderPrice() : "￥" + orderEntity.getOrderPayMoney());
            }
        mAdapter.setModels(models);
        mAdapter.notifyDataSetChanged();
    }

    public void setFootView(String orderStatus) {
        String status = ConverUtil.transOrderStatus(orderStatus, 2);
        switch (status) {
            case "1":
//                        未发货：催促发货 退货
                tvReturn.setVisibility(View.VISIBLE);
                tvPost.setVisibility(View.VISIBLE);

                break;
            case "2":
//                        未收货：查看物流 退货
                tvReturn.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                break;
            case "3":
                /*
                * 评价未实现*/
//                        已完成未评价：删除 查看物流 退货 评价
                tvDelete.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                tvReturn.setVisibility(View.VISIBLE);
                break;
            case "4":
//                        已完成评价：删除 查看物流 追加评价
                tvDelete.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                break;
            case "5":
//                        未支付：取消订单 付款
                tvCancel.setVisibility(View.VISIBLE);
                tvToPay.setVisibility(View.VISIBLE);
                break;
            case "6":
//                        取消：删除
                tvDelete.setVisibility(View.VISIBLE);
                break;

        }
    }

    /**
     * 倒计时
     *
     * @param holder
     * @param orderEntity
     * @param orderCreatTime
     * @param time
     * @param hour
     */
    public void cutDown(BaseViewHolder holder, OrderEntity orderEntity, long orderCreatTime, long time, float hour) {
        long payTime = (long) (60 * 60 * hour);
        long timeNow = System.currentTimeMillis() / 1000;//秒
        long order = orderCreatTime;//秒
        if (timeNow - order < payTime) {
            final int shengyushijian = (int) (payTime - (timeNow - order));
            Observable.interval(1, TimeUnit.SECONDS)
                    .take(shengyushijian)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Long>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Long aLong) {
                            long showTime = shengyushijian - aLong;//秒
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
//前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
                            java.util.Date dt = new Date(showTime * 1000);
                            mAdapter.mineTime = sdf.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00
                            mAdapter.notifyDataSetChanged();
                        }
                    });
        } else {
            // 修改订单状态
            mAdapter.renderStatus(holder, orderEntity, "");
            AVObject avObject = AVObject.createWithoutData("order", orderEntity.getObjectId());
            avObject.put("order_status", this.getResources().getString(R.string.order_cancel));
            avObject.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                    } else {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    public void setStatusTime(OrderEntity entity) {
        String date = entity.getOrderSetttlementTime();
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date dt2 = new Date();
        try {
            dt2 = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//继续转换得到秒数的long型
        long orderTime = dt2.getTime() / 1000;
        if (orderEntity.getOrderStatus() != null && orderEntity.getOrderStatus() == getApplicationContext().getResources().getString(R.string.order_cancel)) {
            cutDown(null, entity, orderTime, 0, 0.5f);
        } else if (orderEntity.getOrderStatus() != null && orderEntity.getOrderStatus() == "0011") {

        } else if (orderEntity.getOrderStatus() == "") {

        } else if (orderEntity.getOrderStatus() != null && orderEntity.getOrderStatus() == "0011") {

        } else {
        }
    }

}
